<?php
/**
 * crcl/base
 *
 * Copyright 2013 CRCL - André Sabosch - info@crcl.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace  crcl\base;

interface IMvc
{
  /**
   * Runs the application
   */
  public static function run();
}

class Mvc implements IMvc
{
  public static function run()
  {
    $oRequest = mvc\Request::getInstance(self::evaluateRequest());
    $oRouter = mvc\Router::getInstance(self::evaluateRouter());
    $oResponse = mvc\Response::getInstance(self::evaluateResponse());

    $oFrontcontroller = new mvc\Frontcontroller();
    $oFrontcontroller->setRequest($oRequest);
    $oFrontcontroller->setRouter($oRouter);
    $oFrontcontroller->setResponse($oResponse);
    $oFrontcontroller->run();
  }

  /** PRIVATE *************************************************************************************/

  private static function evaluateRequest()
  {
    if (\crcl\base\Console::isCli())
    {
      return mvc\Request::TYPE_CONSOLE;
    }
    else
    {
      //tested with external call
      //@codeCoverageIgnoreStart
      return mvc\Request::TYPE_HTTP;
      //@codeCoverageIgnoreEnd
    }
  }

  private static function evaluateRouter()
  {
    if (isset($_SERVER['HTTP_ACCEPT']))
    {
      if ((\strpos($_SERVER['HTTP_ACCEPT'], 'api rest') !== \FALSE) &&
       (\strpos($_SERVER['HTTP_ACCEPT'], 'vnd.crcl') !== \FALSE))
      {
        return mvc\Router::TYPE_REST;
      }
    }
    if (\crcl\base\Console::isCli())
    {
      return mvc\Router::TYPE_CONSOLE;
    }
    //tested with external call
    //@codeCoverageIgnoreStart
    return mvc\Router::TYPE_HTTP;
    //@codeCoverageIgnoreEnd
  }

  private static function evaluateResponse()
  {
    if (\crcl\base\Console::isCli())
    {
      return mvc\Response::TYPE_CONSOLE;
    }
    else
    {
      //tested with external call
      //@codeCoverageIgnoreStart
      return mvc\Response::TYPE_HTTP;
      //@codeCoverageIgnoreEnd
    }
  }
}